package com.im.controller;

import com.im.annotation.Jwt;
import com.im.config.MinioConfig;
import com.im.pojoClass.Result;
import com.im.pojoClass.ResultCode;
import io.minio.MinioClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Api(tags = {"Minio"}, value = "MinioController")
@RestController
@RequestMapping("/minio")
@CrossOrigin
public class MinioController {

    @Autowired
    private MinioConfig minioConfig;

    @Jwt
    @ApiOperation(value = "上传文件", notes = "suffix（0->普通文件,1->图片）")
    @PostMapping("/updateFile")
    public Result updateFile(@RequestParam MultipartFile file, @RequestParam(defaultValue = "0") Integer suffix) {

        // 原文件名
        String fileName = file.getOriginalFilename();
        // 文件后缀名
        String format = fileName.substring(fileName.lastIndexOf(".") + 1);
        // 新文件名 => UUID
        String newFileName = UUID.randomUUID().toString();
        // 文件类型
        String fileType = file.getContentType();

        InputStream newInputStream = null;

        // 将文件MultipartFile类型转为InputStream，便于处理
        try {
            newInputStream = file.getInputStream();
        } catch (IOException e) {
            return new Result(ResultCode.FAILED, "文件预处理失败");
        }

        // 如果是图片
        if (suffix == 1) {
            // 压缩图片，如果tmp暂存文件夹不存在，创建文件夹
            try {
                newInputStream = minioConfig.image_small(file, newFileName, format);
            } catch (IOException e) {
                e.printStackTrace();
                return new Result(ResultCode.FAILED, "图片压缩失败");
            }
        }


        // 创建minio客户端，如果桶为空，自动创建桶
        MinioClient minioClient = null;
        try {
            minioClient = minioConfig.create();
        } catch (Exception e) {
            return new Result(ResultCode.FAILED, "客户端连接失败");
        }

        // Minio上传文件
        try {
            String s = minioConfig.putObject(minioClient, newFileName + "." + format, fileType, newInputStream, newInputStream.available());
            return new Result(ResultCode.SUCCESS, s);
        } catch (Exception e) {
            return new Result(ResultCode.FAILED, "文件上传失败");
        }
    }
}
